package leetcode;

public class LeetCode58 {

    public static void main(String[] args) {
        LeetCode58 leetCode58 = new LeetCode58();
        System.out.println(leetCode58.lengthOfLastWord("a "));
    }

    public int lengthOfLastWord(String s) {
        int count = 0;
        boolean firstWorld = false;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) != ' ') {
                count++;
                firstWorld = true;
            } else if (s.charAt(i) == ' ' && firstWorld)
                return count;
        }
        return count;
    }
//------------------------------------------------------------------

    //先排除空格
    public int lengthOfLastWord1(String s) {
        int end = s.length() - 1;
        while(end >= 0 && s.charAt(end) == ' ') end--;
        if(end < 0) return 0;
        int start = end;
        while(start >= 0 && s.charAt(start) != ' ') start--;
        return end - start;
    }
}
